package com.common;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang.time.StopWatch;

/**
 * 方法运行时间测试
 * @author liuyt
 * @date   2014-11-16 下午3:39:08
 * bolgs   http://www.cnblogs.com/liuyitian/
 */
public class MethodTimeActive111 implements MethodInterceptor {
    /**
     * 自定义map集合，key：方法名，value：[0：运行次数，1：总时间]
     */
    public static Map<String,Long[]> methodTest = new HashMap<String, Long[]>();
    /**
     * 拦截要执行的方法
     */
    public Object invoke(MethodInvocation invocation) throws Throwable {
        // 创建一个计时器
        StopWatch watch = new StopWatch();
        // 计时器开始
        watch.start(); 
        // 执行方法
        Object object = invocation.proceed();
        // 计时器停止
        watch.stop();
        // 方法名称
        String methodName = invocation.getMethod().toGenericString();

     // 获取计时器计时时间
        Long time = watch.getTime();
        Long[] x = null;
        if(methodTest.containsKey(methodName)) {
            x = methodTest.get(methodName);
            x[0]++;
            x[1] += time;
        }else{
            methodTest.put(methodName, new Long[] {1L,time});
        }
        return object;
    }

}
